﻿using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ET;
using BLL;
using System.Globalization;
using HTML;
using System.Web.UI.HtmlControls;
using ERP.Page;

namespace ERP.PageUC
{
    public partial class OrderUC : System.Web.UI.UserControl
    {
        #region[Define]
        private DataTable dtOrderDetailTemp;
        private DataTable dtTotal;
        private Order_Detail_BLL clsOrderDetailTemp = new Order_Detail_BLL();
        private Materials_BLL clsMaterials = new Materials_BLL();
        private Order_Detail_BLL clsOrderDetail = new Order_Detail_BLL();
        private Customer_BLL clsCustomer = new Customer_BLL();
        protected string _TongTienHang = string.Empty;
        protected string _TongTienCK = string.Empty;
        protected string _TongTienVAT = string.Empty;
        protected string _TongTienThanhToan = string.Empty;
        #endregion

        #region[Control]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetOrderDetailTemp();
                txtMaKhachHang.Enabled = false;
                txtTenKhachHang.Enabled = false;
                txtDiaChi.Enabled = false;
            }
        }
        protected void btnSavePopup_Click(object sender, EventArgs e)
        {
            if (lbID.Value == "")
            {
                if (hdMaKH.Value.ToString() == string.Empty)
                {
                    if (Page.Master != null)
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Vui lòng chọn khách hàng !";
                        OpenDialog("#thongbao");
                        ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                }
                if (txtChungTu.Text == string.Empty)
                {
                    if (Page.Master != null)
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Vui lòng nhập vào chứng từ !";
                    OpenDialog("#thongbao");
                    ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                }
                if (ListViewOrderDetailTemp.Items.Count <= 0)
                {
                    if (Page.Master != null)
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Vui lòng chọn hàng hoá !";
                    OpenDialog("#thongbao");
                    ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                }
                if (hdMaKH.Value.ToString() != string.Empty && txtChungTu.Text != string.Empty && ListViewOrderDetailTemp.Items.Count > 0)
                {
                    InsertOrder();
                }
            }
            else
            {
                UpdateOrder();
            }
        }
        protected void btnReloadPopup_Click(object sender, EventArgs e)
        {
            GetOrderDetailTemp();
        }
        protected void btnMaterialsDetail_Click(object sender, EventArgs e)
        {
            txtChungTu.Enabled = false;
            btnAddMaterials_Popup.Attributes["style"] = "display: none";
            //btnMaterialsDetail.Attributes["style"] = "display: inherit";
            //ListViewOrderDetail.Attributes["style"] = "display: inherit";
        }
        protected void btnAddMaterials_Popup_Click(object sender, EventArgs e)
        {
            OpenDialog("#materialorder");
        }
        //List-Item
        protected void ListViewOrderDetailTemp_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                GetOrderDetailTemp();
            }
        }
        protected void ListViewOrderDetailTemp_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            ListViewOrderDetailTemp.EditIndex = -1;
            GetOrderDetailTemp();
        }
        protected void ListViewOrderDetailTemp_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            Label lbID = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("lbID")) as Label;
            Order_Detail_BLL.DeleteOrderDetailTemp(int.Parse(lbID.Text));
           
            ListViewOrderDetailTemp.EditIndex = -1;
            GetOrderDetailTemp();
            if (Page.Master != null)
                ((Label)Page.Master.FindControl("lbThongBao")).Text = "Xoá vật tư ra khỏi danh sách thành công !";
                OpenDialog("#thongbao");
                ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
        }
        protected void ListViewOrderDetailTemp_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            ListViewOrderDetailTemp.EditIndex = e.NewEditIndex;
            GetOrderDetailTemp();
        }
        protected void ListViewOrderDetailTemp_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            try
            {
                Label lbID = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("lbID")) as Label;

                TextBox txtSoLuong = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtSoLuong")) as TextBox;
                TextBox txtDonGia = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtDonGia")) as TextBox;
                Label txtThanhTien = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtThanhTien")) as Label;

                TextBox txtCKPercent = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtCKPercent")) as TextBox;
                TextBox txtCK = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtCK")) as TextBox;

                TextBox txtVATPercent = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtVATPercent")) as TextBox;
                TextBox txtVAT = (ListViewOrderDetailTemp.Items[e.ItemIndex].FindControl("txtVAT")) as TextBox;

                ET.OrderDetailTemp_ET obj = new ET.OrderDetailTemp_ET();
                obj.Order_Detail_Id = int.Parse(lbID.Text);
                obj.Order_Detail_Quality = int.Parse(txtSoLuong.Text);
                obj.Order_Detail_Price = float.Parse(txtDonGia.Text.Replace(",", ""));

                obj.Order_Detail_CK_Percent = float.Parse(txtCKPercent.Text.Replace(",", ""));
                if (txtCKPercent.Text == "0" || txtCKPercent.Text == string.Empty)
                {
                    obj.Order_Detail_CK = 0;
                }
                else
                {
                    obj.Order_Detail_CK = (float.Parse(txtSoLuong.Text.Replace(",", "")) * (float.Parse(txtDonGia.Text.Replace(",", "")) * float.Parse(txtCKPercent.Text.Replace(",", "")))) / 100;
                }

                obj.Order_Detail_VAT_Percent = float.Parse(txtVATPercent.Text.Replace(",", ""));
                if (txtVATPercent.Text == "0" || txtVATPercent.Text == string.Empty)
                {
                    obj.Order_Detail_VAT = 0;
                }
                else
                {
                    obj.Order_Detail_VAT = (float.Parse(txtSoLuong.Text.Replace(",", "")) * (float.Parse(txtDonGia.Text.Replace(",", "")) * float.Parse(txtVATPercent.Text.Replace(",", "")))) / 100;
                }
                obj.Order_Detail_Total_Price = (float.Parse(txtSoLuong.Text) * float.Parse(txtDonGia.Text.Replace(",", ""))) + float.Parse(txtVAT.Text.Replace(",", "")) - float.Parse(txtCK.Text.Replace(",", ""));

                Order_Detail_BLL.UpdateOrderDetailTemp(obj);
                if (Page.Master != null)
                    ((Label)Page.Master.FindControl("lbThongBao")).Text = "Cập nhật thành công danh sách vật tư !";
                OpenDialog("#thongbao");
                ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                ListViewOrderDetailTemp.EditIndex = -1;
                GetOrderDetailTemp();
                Total();
            }
            catch (Exception ex)
            {
                if (Page.Master != null)
                    ((Label)Page.Master.FindControl("lbThongBao")).Text = ex.ToString();
                OpenDialog("#thongbao");
                ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
            }
        }
        protected void ListViewOrderDetailTemp_ItemCreated(object sender, ListViewItemEventArgs e)
        {

        }
        //-----------------------------------
        #endregion

        #region[Fucntion]
        protected bool CheckInsert()
        {
            Order_BLL clsOrder = new Order_BLL();
            bool kiemtra = false;
            DataTable dtOrder = clsOrder.GetOrder();
            if (dtOrder != null && dtOrder.Rows.Count > 0)
            {
                foreach (DataRow dr in dtOrder.Rows)
                {
                    if (txtChungTu.Text == dr["Order_Code"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertOrder()
        {
            try
            {
                if (CheckInsert())
                {
                    if (Page.Master != null)
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Mã chứng từ đã tồn tại !";
                        OpenDialog("#thongbao");
                        ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                }
                else
                {
                    Order_ET obj = new Order_ET();
                    Order_Detail_ET _obj = new Order_Detail_ET();
                    obj.Order_Code = txtChungTu.Text;
                    obj.Order_Date = DateTime.Parse(txtNgayDatHang.Text = txtNgayDatHang.Text == "" ? DateTime.Today.ToString() : txtNgayDatHang.Text);
                    obj.Customer_Id = int.Parse(hdMaKH.Value.ToString());
                    obj.Order_DateBegin = DateTime.Parse(txtNgayDatHang.Text = txtNgayDatHang.Text == "" ? DateTime.Today.ToString() : txtNgayDatHang.Text);
                    obj.Order_DateEnd = DateTime.Parse(txtNgayGiaoHang.Text = txtNgayGiaoHang.Text == "" ? DateTime.Today.ToString() : txtNgayGiaoHang.Text);
                    obj.Order_Payment_Date = DateTime.Parse(txtHangThanhToan.Text = txtHangThanhToan.Text == "" ? DateTime.Today.ToString() : txtHangThanhToan.Text);
                    obj.Order_Transport = float.Parse(txtGiaVanChuyen.Text = txtGiaVanChuyen.Text == "" ? "0" : txtGiaVanChuyen.Text.Replace(",", ""));
                    obj.Order_Note = txtDienGiai.Text;
                    
                    obj.Order_VAT = float.Parse(txtVAT.Text = txtVAT.Text == "" ? "0" : txtVAT.Text);
                    obj.IsActive = false;
                    Order_BLL.Inserttb_Order(obj);
                    for (int i = 0; i < ListViewOrderDetailTemp.Items.Count; i++)
                    {
                        HtmlInputHidden SenderId = (HtmlInputHidden)ListViewOrderDetailTemp.Items[i].FindControl("hiddenId");

                        Label lbID = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lbID");
                        Label lbIDMaterials_Id = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lbIDMaterials_Id");
                        Label lbSoLuong = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lbSoLuong");
                        Label lbDonGia = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lbDonGia");

                        Label lb_lst_ck_percent = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lb_lst_ck_percent");
                        Label lb_lst_ck = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lb_lst_ck");

                        Label lb_lst_vat_pertcent = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lb_lst_vat_pertcent");
                        Label lb_lst_vat = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lb_lst_vat");

                        Label lbThanhTien = (Label)ListViewOrderDetailTemp.Items[i].FindControl("lbThanhTien");

                        _obj.Order_Id = int.Parse(obj.Order_Id.ToString());
                        _obj.Materials_Id = int.Parse(lbIDMaterials_Id.Text);
                        _obj.Order_Detail_Quality = int.Parse(lbSoLuong.Text);
                        _obj.Order_Detail_Price = float.Parse(lbDonGia.Text.Replace(",", ""));

                        _obj.Order_Detail_CK_Percent = int.Parse(lb_lst_ck_percent.Text);
                        _obj.Order_Detail_CK = int.Parse(lb_lst_ck.Text);

                        _obj.Order_Detail_VAT_Percent = int.Parse(lb_lst_vat_pertcent.Text);
                        _obj.Order_Detail_VAT = int.Parse(lb_lst_vat.Text);

                        _obj.Order_Detail_Total_Price = float.Parse(lbThanhTien.Text);
                        _obj.IsActive = false;
                        Order_Detail_BLL.InsertOrderDetail(_obj);
                    }
                    Order_Detail_BLL.DeleteOrderDetailTempAll();
                    GetOrderDetailTemp();
                    upNewUpdatePanel.Update();
                    ((Order)Page).GetOrder();
                    ClearTextBox();
                    if (Page.Master != null)
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Thêm mới thành công phiếu đặt hàng !";
                }
              
            }
            catch (Exception ex)
            {
                if (Page.Master != null) ((Label)Page.Master.FindControl("lbThongBao")).Text = ex.ToString();
            }
            finally
            {
                txtChungTu.Enabled = true;
                OpenDialog("#thongbao");
                if (Page.Master != null) ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
            }
        }
        protected void UpdateOrder()
        {
            try
            {
                Order_ET obj = new Order_ET();
                Order_Detail_ET _obj = new Order_Detail_ET();
                obj.Order_Id = int.Parse(lbID.Value);
                obj.Order_Code = txtChungTu.Text;
                obj.Order_Date = DateTime.Parse(txtNgayDatHang.Text = txtNgayDatHang.Text == "" ? DateTime.Today.ToString() : txtNgayDatHang.Text);
                obj.Customer_Id = int.Parse(hdMaKH.Value.ToString());
                obj.Order_DateBegin = DateTime.Parse(txtNgayDatHang.Text = txtNgayDatHang.Text == "" ? DateTime.Today.ToString() : txtNgayDatHang.Text);
                obj.Order_DateEnd = DateTime.Parse(txtNgayGiaoHang.Text = txtNgayGiaoHang.Text == "" ? DateTime.Today.ToString() : txtNgayGiaoHang.Text);
                obj.Order_Payment_Date = DateTime.Parse(txtHangThanhToan.Text = txtHangThanhToan.Text == "" ? DateTime.Today.ToString() : txtHangThanhToan.Text);
                obj.Order_Transport = float.Parse(txtGiaVanChuyen.Text = txtGiaVanChuyen.Text == "" ? "0" : txtGiaVanChuyen.Text.Replace(",", ""));
                obj.Order_Note = txtDienGiai.Text;
                obj.Order_VAT = float.Parse(txtVAT.Text = txtVAT.Text == "" ? "0" : txtVAT.Text);
                Order_BLL.Updatetb_Order(obj);
            }
            catch (Exception ex)
            {
                if (Page.Master != null) ((Label)Page.Master.FindControl("lbThongBao")).Text = ex.ToString();
            }
            finally
            {
                txtChungTu.Enabled = false;
                ((Order)Page).GetOrder();
                ((Label)Page.Master.FindControl("lbThongBao")).Text = "Cập nhật thành công !";
                OpenDialog("#thongbao");
                if (Page.Master != null) ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
            }
        }
        public void GetOrderDetailTemp()
        {
            dtOrderDetailTemp = clsOrderDetailTemp.GetOrderDetailTemp();
            if (dtOrderDetailTemp != null)
            {
                ListViewOrderDetailTemp.DataSource = dtOrderDetailTemp;
                ListViewOrderDetailTemp.DataBind();
            }
        }
        protected void Total()
        {
            dtTotal = clsOrderDetail.GetOrderDetailTempTotal();
            if (dtTotal != null && dtTotal.Rows.Count > 0)
            {
                _TongTienHang = String.Format("{0:0.00}", dtTotal.Rows[0]["TONG TIEN HANG"].ToString());
                _TongTienCK = dtTotal.Rows[0]["TONG TIEN CK"].ToString();
                _TongTienVAT = dtTotal.Rows[0]["TONG TIEN VAT"].ToString();
                _TongTienThanhToan = String.Format("{0:0.00}", dtTotal.Rows[0]["TONG TIEN THANH TOAN"].ToString());
            }
        }
        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }
        #endregion

        #region[ClearTextbox]
        protected void ClearTextBox()
        {
            txtChungTu.Text = string.Empty;
            txtDiaChi.Text = string.Empty;
            txtMaSoThue.Text = string.Empty;
            txtDienGiai.Text = string.Empty;
            txtMaKhachHang.Text = string.Empty;
            txtTenKhachHang.Text = string.Empty;
            
            txtNgayDatHang.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today.ToString());
            txtNgayGiaoHang.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today.ToString());
            txtHangThanhToan.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today.ToString());
            txtGiaVanChuyen.Text = "0";
            txtVAT.Text = "0";
        }
        #endregion
    }
}